package com.sk.places.places2.presentation.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.logging.Logger;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.sk.places.places2.business.service.UserService;
import com.sk.places.places2.fb.service.FBService;
import com.sk.places.places2.service.entity.UserInfo;
import com.visural.common.StringUtil;
/**
 * To be invoked by Facebook sevice.
 * @author skhurana
 *
 */
public class FBAuthAction  
		implements ServletRequestAware, ServletResponseAware, SessionAware {

	private HttpServletRequest request ;
	private Logger logger = Logger.getLogger(getClass().getName()) ;
	
	@Inject
	private UserService userService ;
	
	@Inject
	private FBService fbService ; 
	private UserInfo userInfo ;
	private Map<String, Object> session ; 

	/*public FBAuthAction(UserService userService, FBService fbService )  { 
		this.userService = userService ;
		this.fbService = fbService ; 
	}*/
	
	public String execute() { 
		try {
			System.out.println("fbauthhhhhhh");
			logger.entering(this.getClass().getName(), "execute");
			logger.info(" userService " + userService +  " fbService " + fbService) ;
	        String code = request.getParameter("code");
	        if (StringUtil.isNotBlankStr(code)) {
	            String authURL = fbService.getAuthURL(code);
	            URL url = new URL(authURL);
                String result = readURL(url);
                String accessToken = null;
                Integer expires = null;
                String[] pairs = result.split("&");
                for (String pair : pairs) {
                    String[] kv = pair.split("=");
                    if (kv.length != 2) {
                        throw new RuntimeException("Unexpected auth response");
                    } else {
                        if (kv[0].equals("access_token")) {
                            accessToken = kv[1];
                        }
                        if (kv[0].equals("expires")) {
                            expires = Integer.valueOf(kv[1]);
                        }
                    }
                }
                if (accessToken != null && expires != null) {
                	userInfo = userService.getFacebookUser(accessToken, expires);
                } else {
                    throw new RuntimeException("Access token and expires not found");
                }	        	
	        }
	        else {
	        	// consider this test.
	        	UserInfo guestUserInfo = new UserInfo() ; 
	        	guestUserInfo.setFirstName("Guest") ;
	        	guestUserInfo.setLastName("visitor") ;
	        	guestUserInfo.setDatevisited(new Date()) ; 
	        	guestUserInfo.setEmail("test" +  new Random().nextFloat()+ "@test.com") ;
	        	userService.save(guestUserInfo) ; 
	        }
			return "success" ;
		} 
		catch(Exception e) {
			e.printStackTrace(); 
			logger.severe(e.getMessage()) ;
			return "error"; 
		}
	}
	
    private String readURL(URL url) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = url.openStream();
        int r;
        while ((r = is.read()) != -1) {
            baos.write(r);
        }
        return new String(baos.toByteArray());
    }
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		//this.response = response ; 
		
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request ; 
		
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session ;
		
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public FBService getFbService() {
		return fbService;
	}

	public void setFbService(FBService fbService) {
		this.fbService = fbService;
	} 
	
	

}
